要如何在 Fragment 或是 Activity 中取得元件並將資料呈現上去呢?透過 ViewBinding 可以輕鬆操作元件,程式碼也會變得更簡潔,我們就來看看什麼是 ViewBinding 吧!以下如有解釋不清或是描述錯誤的地方還請大家多多指教:
除了 ViewBinding 之外還有哪些方式可以取得 view 的元件呢?
lateinit var cityTitle: TextView
cityTitle = findViewById(R.id.cityTitle)
cityTitle.text = "London"
@BindView(R.id.cityTitle)
lateinit var cityTitle: TextView
...
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(this, R.layout.activity_main)
ButterKnife.bind(this)
}
// get id name
cityTitle.text = "London"
但目前 Kotlin Android Extensions 要被棄用了,官方建議改用 ViewBinding,如果本身有在使用 Parcelize 的人,改 import
kotlin-parcelize plugin
// get id name
binding.cityTitle.text = "Lodon"
除了寫法較簡潔之外有以下兩個特點:
@Nullable
android {
...
buildFeatures {
viewBinding true
}
}
接下來要將 Activity 和 Fragment 做 binding 的動作
class MainActivity : AppCompatActivity() {
private lateinit var binding : ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
}
}
class HomeFragment : Fragment() {
private var _binding : FragmentHomeBinding ? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentHomeBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupView()
}
private fun setupView() = binding.apply {
// get view set view
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}